package net.shouyong.topbilliards;

import android.graphics.Color;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.bruce.pickerview.popwindow.DatePickerPopWin;

import net.shouyong.topbilliards.bean.BilliardRecord;
import net.shouyong.topbilliards.fragment.HistoryBillirdrecordFragment;
import net.shouyong.topbilliards.fragment.HomeFragment;

import java.util.Arrays;
import java.util.List;

public class Main2Activity extends AppCompatActivity implements HomeFragment.OnListFragmentInteractionListener {

    public static final String HOME = "home";
    public static final String DETAIL = "detail";

    private ProgressBar progressBar;
    private TextView totalCost;
    private Button chooseDate;
    private DatePickerPopWin pickerPopWin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
//        progressBar = (ProgressBar)findViewById(R.id.progressBar);

        totalCost = (TextView)findViewById(R.id.today_cost);
        chooseDate = (Button)findViewById(R.id.choose_date);
        pickerPopWin = new DatePickerPopWin.Builder(this, new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                String selectDay = String.format("%s-%s-%d", year, month, day);
                if (Utils.getTodayData().equals(selectDay)) {
                    changeToHomeFragment();
                    return;
                }

                changeToHistoryBillirdrecordFragment(selectDay);
                updateTodayTotalCost(selectDay);
            }
        }).textConfirm("确定") //text of confirm button
                .textCancel("取消") //text of cancel button
                .btnTextSize(16) // button text size
                .viewTextSize(25) // pick view text size
                .colorCancel(Color.parseColor("#999999")) //color of cancel button
                .colorConfirm(Color.parseColor("#009900"))//color of confirm button
                .minYear(2016) //min year in loop
                .maxYear(2020) // max year in loop
                .showDayMonthYear(true) // shows like dd mm yyyy (default is false)
                .dateChose(Utils.getTodayData()) // date chose when init popwindow
                .build();

        chooseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickerPopWin.showPopWin(Main2Activity.this);
            }
        });
        changeToHomeFragment();
        updateTodayTotalCost(Utils.getTodayData());
    }

    private void changeToHomeFragment() {

        // Begin the transaction
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // Replace the contents of the container with the new fragment
        ft.replace(R.id.your_placeholder, new HomeFragment(), HOME);
        // or ft.add(R.id.your_placeholder, new FooFragment());
        // Complete the changes added above
        ft.commit();

    }

    public void showProgressBar() {
        if (progressBar == null) {
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
    }

    public void hideProgressBar() {
        if (progressBar == null) {
            return;
        }
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void onListFragmentInteraction(BilliardRecord item) {
        Log.e("FragmentInteraction", item.toString());
    }

    @Override
    public void updateTodayTotalCost( String date) {
        if (totalCost == null ){
            return;
        }

        final String tdate = date == null ?Utils.getTodayData() :date;


        AVQuery<BilliardRecord> query2 = AVObject.getQuery(BilliardRecord.class);
        query2.whereExists(BilliardRecord.END_TIME);

        AVQuery<BilliardRecord> query1 = AVObject.getQuery(BilliardRecord.class);
        query1.whereContains(BilliardRecord.START_TIME, tdate);

        AVQuery<BilliardRecord> query = AVQuery.and(Arrays.asList(query2,query1));
//        query.selectKeys(Arrays.asList(BilliardRecord.COST));
        query.findInBackground(new FindCallback<BilliardRecord>() {


            @Override
            public void done(List<BilliardRecord> list, AVException e) {
                if (e != null) {
                    e.printStackTrace();
                    return;
                }
                if (list == null) {
                    return;
                }
                int total = 0;
                for (BilliardRecord record : list) {
//                    Log.e("total", record.getObjectId()+"");
//                    Log.e("total", record.getSettlement()+"");
                    total += record.getSettlement();
                }

                totalCost.setText(String.format(getString(R.string.today_cost), tdate, String.valueOf(total)));
            }
        });


    }

    private void changeToHistoryBillirdrecordFragment(String date) {
        // Begin the transaction
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        // Replace the contents of the container with the new fragment
        ft.replace(R.id.your_placeholder, HistoryBillirdrecordFragment.newInstance(1,date), DETAIL);
        // or ft.add(R.id.your_placeholder, new FooFragment());
        // Complete the changes added above
        ft.commit();

    }

}
